package com.sctvcloud.zhaohua_sd.ui.utils;

import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.AlertDialogFragment;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * 权限获取工具
 * Created by raoweiwei on 2017/8/25.
 */

public class PermissionUtils {
    private BaseActivity mActivity;
    private ArrayList<String> mPermissionList = new ArrayList<>();
    private AlertDialogFragment mPermissionDialog;
    private PermissionListener mListener;

    public static final int PERMISSIONS_REQUEST_CODE = 1000;

    public PermissionUtils(BaseActivity activity) {
        mActivity = activity;
        mPermissionList = new ArrayList<>();
    }

    /**
     * 添加权限
     */
    public void addPermission(String permission) {
        mPermissionList.add(permission);
    }
    public void setPermissionListener(PermissionListener listener) {
        mListener = listener;
    }

    /**
     * 检查当前是否已获取到传入的权限列表中的所有权限，如果已全部获取，返回 true，如果没有全部获取则返回 false，并在Android系统大于6.0时开启动态权限请求，
     * 此时需要在 Activity 的 onRequestPermissionsResult 方法中监听用户对于权限的操作
     */
    public boolean checkAndRequestPermissions() {
        Iterator<String> it = mPermissionList.iterator();
        while (it.hasNext()) {
            String permission = it.next();
            int hasPermission = ContextCompat.checkSelfPermission(mActivity, permission);
            if (hasPermission == PackageManager.PERMISSION_GRANTED) {
                JLog.e("权限授予成功：" + permission);
                it.remove();
            } else {
                JLog.e("权限授予失败：" + permission);
            }
        }

        if (mPermissionList.size() == 0) {
            return true;
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String[] permissions = mPermissionList.toArray(new String[0]);
                ActivityCompat.requestPermissions(mActivity, permissions, PERMISSIONS_REQUEST_CODE);
            }
            return false;
        }
    }

    /**
     * 重新检查是否获取到了所有权限，如果存在未获取到的权限，则打开提示对话框让用户知晓这些权限的意义
     *
     * @param msg 显示在提示对话框中的权限解释内容
     */
    public boolean recheckPermissions(int[] grantResults, String msg) {
        int length = grantResults.length;
        boolean re_request = false;//标记位：如果需要重新授予权限，true；反之，false
        boolean noRemain = false;//用户是否设置了不再提醒
        for (int i = 0; i < length; i++) {
            if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                JLog.e("权限授予成功:" + mPermissionList.get(i));
            } else {
                JLog.e("权限授予失败:" + mPermissionList.get(i));
                re_request = true;
                boolean show = ActivityCompat.shouldShowRequestPermissionRationale(mActivity, mPermissionList.get(i));
                if (!show) {
                    noRemain = true;
                }
            }
        }
        if (re_request) {
            if (!noRemain) {
                showPermissionDialog(msg);
            } else if (mListener != null) {
                mListener.onUserRefusesPermissions();
            }
            return false;
        } else {
            return true;
        }
    }

    private void showPermissionDialog(String msg) {
      //  if (mPermissionDialog == null) {
            mPermissionDialog = new AlertDialogFragment();
            mPermissionDialog.setCancelOut(false);
            mPermissionDialog.setTitleStr("权限请求说明");
            mPermissionDialog.setMsgGravity(Gravity.LEFT);
            mPermissionDialog.setMsgStr(msg);
            mPermissionDialog.setOkStr("授予");
            mPermissionDialog.setCancleStr("拒绝");
            mPermissionDialog.setOnViewClick(new AlertDialogFragment.OnViewClick() {
                @Override
                public boolean onViewClick(View view, int viewItem, int mode) {
                    if (viewItem == AlertDialogFragment.VIEW_ITEM_OK) {
                        mPermissionDialog.dismissAllowingStateLoss();
                        checkAndRequestPermissions();
                    } else if (mListener != null) {
                        mListener.onUserRefusesPermissions();
                    }
                    return true;
                }
            });
        //}
        mActivity.safeShowDialog(mPermissionDialog, "permission");
    }

    public interface PermissionListener {
        /**
         * 当用户没有全部同意所有权限之后触发的回调
         */
        void onUserRefusesPermissions();
    }
}
